//
//  MYGCalendarViewController.swift
//  MYGrow
//
//  Created by Mo on 2024/3/12.
//

import UIKit
import FSCalendar
import JXPagingView
import JXSegmentedView

class MYGCalendarViewController: MYGBaseController {
//    fileprivate weak var calendar: FSCalendar!
    var monthStr:String = ""
    var calenderList:[calenderListModel] = []
    var currentDate:String!
    private var sectionArr:Array<MYGScheduleModel> = []
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        monthStr = formatter.string(from: Date())
        getCalendarDatasource()
    }
    private func getCalendarDatasource(){
        MMYGNetwork<MYGScheduleAPI, calenderListResponseModel>.request(target: .calendarList(params: ["set_date":monthStr,"doctor_id":MYGUserManager.user?.doctor.id ?? 0])) {[weak self] result in
            self?.calenderList = result?.calenderdata ?? []
            self?.calendar.reloadData()
            self?.getDaySchedules(date: Date())
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    func getDaySchedules(date:Date){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let currentDateString = formatter.string(from: date)
        currentDate = currentDateString
        MMYGNetwork<MYGScheduleAPI, MYGScheduleBaseModel>.request(target: .scheduleList(params: ["doctor_id":MYGUserManager.user?.doctor.id ?? 0,"set_date":currentDateString])) {[weak self] result in
            self?.sectionArr.removeAll()
            let mode:MYGScheduleBaseModel = result ?? MYGScheduleBaseModel()
            self?.sectionArr = mode.data
            self?.calendarTable.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    func refreshSchedule(){
        MMYGNetwork<MYGScheduleAPI, MYGScheduleBaseModel>.request(target: .scheduleList(params: ["doctor_id":MYGUserManager.user?.doctor.id ?? 0,"set_date":currentDate ?? ""])) {[weak self] result in
            self?.sectionArr.removeAll()
            let mode:MYGScheduleBaseModel = result ?? MYGScheduleBaseModel()
            self?.sectionArr = mode.data
            self?.calendarTable.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    func initUI() {
        view.addSubview(calendar)
        calendar.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(310)
        }

        calendar.calendarHeaderView.addSubview(calendarHeaderV)
        calendarHeaderV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        calendarHeaderV.addSubview(titleLab)
        titleLab.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        view.addSubview(calendarTable)
        calendarTable.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(calendar.snp.bottom).offset(7.5)
        }
    }
    private lazy var calendarTable: UITableView = {
        let cont = UITableView(frame: CGRectZero, style: .grouped)
        cont.delegate = self
        cont.dataSource = self
        cont.separatorStyle = .none
        cont.backgroundColor = .rgba(240, 240, 240)
        return cont
    }()
    private lazy var calendar: FSCalendar = {
        let cont = FSCalendar()
        cont.dataSource = self
        cont.delegate = self
        cont.register(FSCalendarCell.self, forCellReuseIdentifier: "myExcell")
        cont.locale = Locale(identifier: "zh-CN")
        cont.accessibilityIdentifier = "calendar"
        cont.appearance.headerDateFormat = "yyyy月MM月"
        cont.appearance.caseOptions = [.weekdayUsesSingleUpperCase]
        cont.appearance.subtitleDefaultColor = .red
        return cont
    }()
    private lazy var calendarHeaderV: FSCalendarHeaderView = {
        let vi = FSCalendarHeaderView()
        vi.backgroundColor = .white
        return vi
    }()
    private lazy var titleLab: UILabel = {
        let vi = UILabel()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        vi.text = formatter.string(from: Date())
        vi.textColor = .black
        return vi
    }()
    override var hideNavigationController: Bool {
        true
    }
}
extension MYGCalendarViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sche:MYGScheduleModel = sectionArr[section]
        return sche.lists.count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionArr.count
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 95
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerV = UIView()
        return headerV
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MYGCalendarScheduleTableViewCell(style: .default, reuseIdentifier: "MYGCalendarScheduleTableViewCell")
        cell.selectionStyle = .none
        let sche:MYGScheduleModel = sectionArr[indexPath.section]
        let scheDetail:MYGScheduleListModel = sche.lists[indexPath.row]
        cell.model = scheDetail
        cell.selectBlock = {[weak self] in
            self?.changeStatus(str: "\(scheDetail.id)")
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = MYGScheduleDetailViewController()
        let sche:MYGScheduleModel = sectionArr[indexPath.section]
        let scheDetail:MYGScheduleListModel = sche.lists[indexPath.row]
        vc.scheModel = scheDetail
        self.navigationController?.pushViewController(vc)
    }
    private func changeStatus(str:String){
        MYGLoading.show()
        MYGNetwork<MYGScheduleAPI, MYGEmptyModel>.request(target: .changeScheduleStatue(param: str)) {[weak self] result in
            MYGLoading.hide()
            self?.refreshSchedule()
        } failed: { _, error in
            MYGLoading.hide()
        }
    }
}
extension MYGCalendarViewController:FSCalendarDataSource,FSCalendarDelegate{
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        // 当月份改变时调用此方法
        let currentDate = calendar.currentPage
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月"
        let formatter2 = DateFormatter()
        formatter2.dateFormat = "yyyy-MM"
        let currentDateString = formatter.string(from: currentDate)
        titleLab.text = currentDateString
        print("Current date: \(currentDateString)")
        monthStr = formatter2.string(from: currentDate)
        getCalendarDatasource()
    }
    func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd"
        let str = formatter.string(from: date)
        if calenderList.count > 0 {
            for ind in 0...calenderList.count - 1 {
                if ind + 1 == Int(str){
                    let mod = calenderList[ind]
                    if  "\(mod.count)" == "1"{
                        return 1
                    }else{
                        return 0
                    }
                }
            }
        }

        return 0
    }
    func calendar(_ calendar: FSCalendar, imageFor date: Date) -> UIImage? {
        return UIImage(named: "collect")
    }
    func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd"
        let str = formatter.string(from: date)
        if calenderList.count > 0 {
            for ind in 0...calenderList.count - 1 {
                if ind + 1 == Int(str){
                    let mod = calenderList[ind]
                    if  "\(mod.count)" == "0" || "\(mod.count)" == "1"{
                        return ""
                    }else{
                        return "(\(mod.count))"
                    }
                }
            }
        }

        return ""
    }
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        getDaySchedules(date: date)
    }
    
}
extension MYGCalendarViewController:JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        view
    }
}
